package app.controllers.dishes;

import app.models.dishes.Category;
import com.ifonly.activerecord.DbUtils;
import com.ifonly.activerecord.Record;
import com.ifonly.activerecord.sql.config.Sql;
import com.ifonly.mvc.ActionKey;
import com.ifonly.mvc.Controller;

/**
 * @author ifonly
 * @version 1.0 2016-01-28 15:55
 * @since JDK 1.6
 */
public class CategoryController extends Controller {

    @ActionKey("")
    public void index() {
        render("index");
    }

    public void dt() {
        renderDataTables(Category.class);
    }

    public void delete() {
        int id = getInt(0, 0);
        if (id == 0) {
            renderFailed("参数不正确");
            return;
        }
        Record record = DbUtils.query(Sql.get("category.dishCount"), id);
        if (record == null || (record.getNumber("count") != null && record.getNumber("count").longValue() == 0)) {
            DbUtils.delete(Sql.get("category.deleteById"), id);
            renderSuccess();
            return;
        }
        renderFailed("当前菜品类型关联了菜品, 无法删除!");
    }

    public void item() {
        int id = getInt(0, 0);
        Category category;
        if (id == 0) {
            category = new Category();
        } else {
            category = Category.findByPrimaryKey(Category.class, id);
        }
        setAttr("category", category);
        render("item");
    }

    public void save() {
        Category category = getModel(Category.class);
        if (DbUtils.isNew(category)) {
            category.save();
        } else {
            category.update();
        }
        redirect("");
    }

}
